import { useState, useEffect } from 'react'
import { Button, Input, message } from 'antd'
import styled from 'styled-components'
import TodoItem from './TodoItem'
import _ from '@/assets/utils'

// 组件样式
const TodoListStyle = styled.div`
    box-sizing: border-box;
    margin: 0 auto;
    width: 400px;
    .header {
        display: flex;
        align-items: center;
        padding-bottom: 20px;
        padding-top: 20px;
        border-bottom: 1px dashed #AAA;
        .ant-btn {
            margin-left: 10px;
        }
    }
    .main {
        padding-top: 20px;
        .item {
            margin-bottom: 20px;
            font-size: 14px;
            .ant-btn {
                margin-right: 10px;
            }
            .ant-input {
                width: 60%;
            }
            .text {
                padding-bottom: 10px;
            }
        }
    }
`

export default function TodoList() {
    // 定义状态
    let [text, setText] = useState(''),
        [list, setList] = useState(() => {
            // 只有组件第一次渲染才会执行
            let data = _.storage.get('CACHE_TASKLIST')
            return data || []
        })

    // 监听任务列表的变化，存储到本地
    useEffect(() => {
        _.storage.set('CACHE_TASKLIST', list)
    }, [list])

    // 新增任务
    const submit = () => {
        if (text.length === 0) {
            message.warning('任务描述不能为空!')
            return
        }
        list.push({
            id: +new Date(),
            text
        })
        setList([...list])
        setText('')
    }

    // 修改/删除任务
    const handle = (type, id, updateText) => {
        if (type === 'update') {
            // 修改任务
            list = list.map(item => {
                if (+item.id === +id) {
                    item.text = updateText
                }
                return item
            })
            setList(list)
            return
        }
        // 删除任务
        list = list.filter(item => +item.id !== +id)
        setList(list)
    }

    return <TodoListStyle>
        <div className="header">
            <Input placeholder="请输入任务描述"
                value={text}
                onChange={ev => {
                    setText(ev.target.value.trim())
                }} />
            <Button type="primary" onClick={submit}>新增任务</Button>
        </div>
        <ul className="main">
            {list.map(item => {
                return <TodoItem key={item.id}
                    info={item}
                    handle={handle} />
            })}
        </ul>
    </TodoListStyle >
}